package com.schrodinger.zwebservice.axis2.client.wsconfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

import com.schrodinger.zwebservice.axis2.client.util.WebserviceDom4jUtils;
/**
 * webservice配置文件管理类
 * @author asus
 *
 */
public class WSConfigManager {
	private static Map<String, WSConfigInfo> cacheMap = null;
	static {
		cacheMap = new HashMap<String, WSConfigInfo>();
		loadWSConfig();
	}	

	// 单实例构造方法
	private WSConfigManager() {
		super();
	}

	public static boolean hasItem(String key) {
		return cacheMap.containsKey(key);
	}

	// 载入配置项
	public static void putItem(String key, WSConfigInfo serverInfo) {
		cacheMap.put(key, serverInfo);
	}

	// 载入配置项
	public static WSConfigInfo getItem(String key) {
		return cacheMap.get(key);
	}

	// 清除指定的配置项
	public static void removeItem(String key) {
		cacheMap.remove(key);
	}

	// 清除所有配置项
	public static void clearAll() {
		cacheMap.clear();
	}

	// 获取缓存对象中的所有键值名称
	public static List<String> getCacheAllkey() {
		List<String> a = new ArrayList<String>();
		try {
			Iterator<java.util.Map.Entry<String, WSConfigInfo>> i = cacheMap
					.entrySet().iterator();
			while (i.hasNext()) {
				java.util.Map.Entry<String, WSConfigInfo> entry = i.next();
				a.add(entry.getKey());
			}
		} catch (Exception ex) {
		} finally {
		}
		return a;
	}
	
	/**
	 * 加载webservice服务端配置文件
	 */
	public static void loadWSConfig() {
		Document doc = WebserviceDom4jUtils.getDocument("WebServiceConfig.xml");
		Element root = doc.getRootElement();
		List<Element> webServiceList = root.elements();
		for (Iterator<Element> it = webServiceList.iterator(); it.hasNext();) {
			Element element = it.next();
			String serviceMark = element.attributeValue("serviceMark");
			String ip = element.element("ip").getTextTrim();
			String port = element.element("port").getTextTrim();
			String contextPath = element.element("contextpath").getTextTrim();
			String timeout = element.element("timeout").getTextTrim();

			if (ip.startsWith("http")) {
				ip = ip.substring(6);
			}
			String remoteServiceURI = "http://" + ip;
			if (StringUtils.isNotBlank(port)) {
				remoteServiceURI += (":" + port);
			}
			if (StringUtils.isNotEmpty(contextPath)) {
				remoteServiceURI += ("/" + contextPath);
			}
			timeout = timeout == null ? "0" : timeout;

			WSConfigInfo serverInfo = new WSConfigInfo();
			serverInfo.REMOTE_SERV_URI = remoteServiceURI;
			serverInfo.END_POINT_URL = remoteServiceURI + "/services/";
			serverInfo.WS_REQUEST_TIMEOUT = Long.parseLong(timeout);
			WSConfigManager.putItem(serviceMark, serverInfo);
		}
	}
}
